package com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.CProgressDialogUtils;
import com.jess.arms.utils.LogUtils;
import com.xiaoxing.zhinenghuacangku_liaocheng.R;
import com.xiaoxing.zhinenghuacangku_liaocheng.R2;
import com.xiaoxing.zhinenghuacangku_liaocheng.di.component.DaggerLiaoCheng_SaoMaTuiKuComponent;
import com.xiaoxing.zhinenghuacangku_liaocheng.di.module.LiaoCheng_SaoMaTuiKuModule;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.contract.LiaoCheng_SaoMaTuiKuContract;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.model.entity.GetUserSpaceListForAutoStore;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.presenter.LiaoCheng_SaoMaTuiKuPresenter;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.dbbase.LikuBaocunmidnum;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.entity.LiaoCheng_SaoMaTuiKu;
import com.xw.repo.XEditText;

import org.jetbrains.annotations.NotNull;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_LIAO_CHENG_ACTIVITY_LIAO_CHENG_SAO_MA_TUI_KU)
public class LiaoCheng_SaoMaTuiKuActivity extends BaseActivity<LiaoCheng_SaoMaTuiKuPresenter> implements LiaoCheng_SaoMaTuiKuContract.View {


    @BindView(R2.id.img_er_wei_ma)
    ImageView imgErWeiMa;
    @BindView(R2.id.ns_ku_wei)
    NiceSpinner nsKuWei;
    @BindView(R2.id.ns_ru_ku_wei)
    NiceSpinner nsRuKuWei;
    @BindView(R2.id.ll_xuan_ze_ku_wei)
    LinearLayout llXuanZeKuWei;
    @BindView(R2.id.xet_shu_liang)
    XEditText xetShuLiang;
    @BindView(R2.id.img_tuo_pan_ma)
    ImageView imgTuoPanMa;
    @BindView(R2.id.ll_tian_xie_shu_liang)
    LinearLayout llTianXieShuLiang;

    @BindView(R2.id.tv_yi_sao_miao_er_wei_ma)
    TextView tvYiSaoMiaoErWeiMa;
    @BindView(R2.id.tv_sao_miao_wu_liao_er_wei_ma)
    TextView tvSaoMiaoWuLiaoErWeiMa;
    @BindView(R2.id.tv_yi_sao_miao_tuo_pan_ma)
    TextView tvYiSaoMiaoTuoPanMa;
    private String scanMidResult = "";
    private String scanTuoPanMaResult = "";
    private String mCangWei = "";
    private String mnsKuWeiName = "";
    private String mnsKuWeiId = "";
    private int mSelectedSpid = 0;
    private int duiduojixuhao = 0;
    private String type;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiaoCheng_SaoMaTuiKuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .liaoCheng_SaoMaTuiKuModule(new LiaoCheng_SaoMaTuiKuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_liao_cheng__sao_ma_tui_ku; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_liao_cheng__sao_ma_tui_ku));
        //getLiaoCheng_SaoMaTuiKuData();
        type = getIntent().getExtras().getString("type");

        if (type.equals("0")) {
            tvSaoMiaoWuLiaoErWeiMa.setVisibility(View.VISIBLE);
            imgErWeiMa.setVisibility(View.VISIBLE);
        } else if (type.equals("1")) {
            tvSaoMiaoWuLiaoErWeiMa.setVisibility(View.GONE);
            imgErWeiMa.setVisibility(View.GONE);
            String mid = getIntent().getExtras().getString("mid");
            scanMidResult = mid;
            tvYiSaoMiaoErWeiMa.setText("物料mid：" + mid);
            validateReturnInstore(mid);
        }

    }

    @Override
    public void getLiaoCheng_SaoMaTuiKuDataSuccess(LiaoCheng_SaoMaTuiKu entityData) {


    }

    private void getLiaoCheng_SaoMaTuiKuData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getLiaoCheng_SaoMaTuiKuData(map);
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick({R2.id.img_er_wei_ma, R2.id.img_tuo_pan_ma, R2.id.btn_zhi_xing_cao_zuo_1, R2.id.btn_zhi_xing_cao_zuo_2})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.img_er_wei_ma) {
            llXuanZeKuWei.setVisibility(View.GONE);
            llTianXieShuLiang.setVisibility(View.GONE);
            mCangWei = "";
            scanMidResult = "";
            scanTuoPanMaResult = "";
            tvYiSaoMiaoErWeiMa.setText("已扫描的二维码：" + scanMidResult);
            toScanQRCodeActivity();
        } else if (id == R.id.img_tuo_pan_ma) {
            toScanTuoPanMaCodeActivity();
        } else if (id == R.id.btn_zhi_xing_cao_zuo_1) {
            returnGetMaterialPlate(scanMidResult, mnsKuWeiId, mSharedPreferencesHelper.getString(BaseConstants.UID));
        } else if (id == R.id.btn_zhi_xing_cao_zuo_2) {

            if (TextUtils.isEmpty(getShuLiang())) {
                showMessage("请填写数量");
                return;
            }
            if (mSelectedSpid == 0) {
                showMessage("请选择入库位");
                return;
            }
            if (TextUtils.isEmpty(scanTuoPanMaResult)) {
                showMessage("请扫描托盘码");
                toScanTuoPanMaCodeActivity();
                return;
            }
            instoreCallliKuGroupWithSALVERID(scanMidResult);
        }

    }

    @NotNull
    private String getShuLiang() {
        return xetShuLiang.getText().toString().trim();
    }

    private void bindCangWeiNsData() {

        ArrayList<String> dataNames = new ArrayList();
        ArrayList<String> ids = new ArrayList();

        dataNames.add("S1_01");
        dataNames.add("S1_02");
        ids.add("1");
        ids.add("2");

        nsKuWei.attachDataSource(dataNames);
        mnsKuWeiName = dataNames.get(0);
        mnsKuWeiId = ids.get(0);

        nsKuWei.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mnsKuWeiName = dataNames.get(0);
                mnsKuWeiId = ids.get(0);
            }
        });

    }

    private void toScanQRCodeActivity() {
        Intent openCameraIntent = new Intent(this, LiaoCheng_ScanQRCodeActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
        startActivityForResult(openCameraIntent, 101);
    }

    private void toScanTuoPanMaCodeActivity() {
        Intent openCameraIntent = new Intent(this, LiaoCheng_ScanQRCodeActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 102);
        startActivityForResult(openCameraIntent, 102);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle bundle = data.getExtras();
            scanMidResult = bundle.getString("scan_result");
            tvYiSaoMiaoErWeiMa.setText("已扫描的二维码：" + scanMidResult);
            validateReturnInstore(scanMidResult);
        }
        if (resultCode == 102) {
            Bundle bundle = data.getExtras();
            scanTuoPanMaResult = bundle.getString("scan_result");
            tvYiSaoMiaoTuoPanMa.setText("已扫描的托盘码：" + scanTuoPanMaResult);
            showMessage("请再点击执行操作按钮，执行退库操作");
        }

    }

    /**
     * @param
     * @return
     * @method
     * @description 扫描完物料二维码执行的方法   如果是"Error"  则提示查询错误   (1)如果是仓位,比如"A01-02-06-24" 则保存到变量中   调用returnGetMaterialPlate 方法
     * @date: 2021/1/21 0021 14:36
     * @author: 小星
     */
    private void validateReturnInstore(String mid) {

        showLoading();
        String methodName = "ValidateReturnInstore";
        SoapParams params = new SoapParams();
        params.put("mid", mid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                    if (!result.equals("0") && result.contains("-")) {
                        mCangWei = result;
                        llXuanZeKuWei.setVisibility(View.VISIBLE);
                        bindCangWeiNsData();
                    } else if (result.equals("0")) {
                        llTianXieShuLiang.setVisibility(View.VISIBLE);
                        getUserSpaceListForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID), "");
                    } else {
                        showMessage("查询错误" + result);
                    }


                } else {
                    showMessage("查询错误");
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * @param
     * @return
     * @method
     * @description (1)如果是仓位, 比如"A01-02-06-24" 则保存到变量中    调用此方法
     * @date: 2021/1/21 0021 14:49
     * @author: 小星
     */
    private void returnGetMaterialPlate(String mid, String instoreBufferId, String uid) {

        showLoading();
        String methodName = "ReturnGetMaterialPlate";
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("instoreBufferId", instoreBufferId);
        params.put("uid", uid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                try {
                    String result = object.getProperty(methodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        if (Integer.parseInt(result) > 0) {
                            showMessage("执行成功");
                        } else {
                            showMessage("执行失败");
                        }
                    } else {
                        showMessage("执行失败");
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void instoreCallliKuGroupWithSALVERID(String mid) {

        showLoading();
        String methodName = "InstoreCallliKuGroupWithSALVERID";
        SoapParams params = new SoapParams();
        ArrayList<LikuBaocunmidnum> listss = new ArrayList<>();
        LikuBaocunmidnum likuBaocunmidnum = new LikuBaocunmidnum();
        likuBaocunmidnum.setMid(mid);
        likuBaocunmidnum.setNum(getShuLiang());
        listss.add(likuBaocunmidnum);
        JSONArray jsonArray = (JSONArray) JSON.toJSON(listss);
        params.put("modelJson", jsonArray.toJSONString());
        params.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("spid", String.valueOf(mSelectedSpid));
        params.put("remark", "");
        params.put("SALVERID", scanTuoPanMaResult);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                try {
                    String result = object.getProperty(methodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        if (Integer.parseInt(result) > 0) {
                            showMessage("执行成功");
                        } else {
                            showMessage("执行失败");
                        }
                    } else {
                        showMessage("执行失败");
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * @param
     * @return
     * @method
     * @description 查询入库位置
     * @date: 2021/1/21 0021 15:30
     * @author: 小星
     */
    private void getUserSpaceListForAutoStore(String user_id, String spname) {
        showLoading();

        String methodName = "GetUserSpaceListForAutoStoreQingDao";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("spname", spname);
        params.put("ismeter", String.valueOf(duiduojixuhao));
        LogUtils.debugEInfo("ismeter==" + duiduojixuhao);

        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    try {

                        List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = ArmsUtils.parseString2List(result, GetUserSpaceListForAutoStore.class);
                        if (getUserSpaceListForAutoStoreList.size() > 0) {

                            initSpPosition(getUserSpaceListForAutoStoreList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void initSpPosition(List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList) {
        ArrayList<String> spnames = new ArrayList<String>();
        ArrayList<String> listSpids = new ArrayList<String>();
        HashMap<String, GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreHashMap = new HashMap<>();

        for (int i = 0; i < getUserSpaceListForAutoStoreList.size(); i++) {
            spnames.add(getUserSpaceListForAutoStoreList.get(i).getSpname());
            listSpids.add(String.valueOf(getUserSpaceListForAutoStoreList.get(i).getSpid()));
            getUserSpaceListForAutoStoreHashMap.put(getUserSpaceListForAutoStoreList.get(i).getSpname(), getUserSpaceListForAutoStoreList.get(i));
        }
        nsRuKuWei.attachDataSource(spnames);
        if (nsRuKuWei.getDataSet().size() > 0) {
            GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = getUserSpaceListForAutoStoreHashMap.get(nsRuKuWei.getFullWidthAdapter().getItem(0));
            mSelectedSpid = getUserSpaceListForAutoStore.getSpid();
            LogUtils.debugEInfo("spid==" + mSelectedSpid);
        }


        nsRuKuWei.setGravity(Gravity.LEFT);
        nsRuKuWei.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GetUserSpaceListForAutoStore getUserSpaceListForAutoStore = getUserSpaceListForAutoStoreHashMap.get(nsRuKuWei.getFullWidthAdapter().getItem(position));
                mSelectedSpid = getUserSpaceListForAutoStore.getSpid();
            }
        });
    }
}
